import unittest
import optparse
from os.path import join, exists
from os import getcwd, mkdir
import shutil
import sys
from Autotests.TestRunner import HTMLTestRunner
from Autotests.Cloud.executor import ActionExecutor as executor
from Reporting.Mailer import Mailer

parser = optparse.OptionParser()
parser.add_option('-s', '--startDir', type = 'string', dest = 'startDir', help = 'root dir for tests discover')
parser.add_option('-p', '--pattern', type = 'string', dest = 'pattern', default = "*.py", help = 'test files pattern')

recipients = ["andrei.tsishenka@iaso.com",
              "vasili@iaso.com",
              "roman@iaso.com",
              "aleksey@iaso.com",
              "tatyana.shakirova@iaso.com",
              "alexandra.yedinovich@iaso.com",
              "sergey.gradovich@iaso.com"]


def main(rootPath, pattern):
    logsPath = join(getcwd(), 'Logs')
    if exists(logsPath):
        shutil.rmtree(logsPath)
    mkdir(logsPath)

    loader = unittest.TestLoader()
    tests = loader.discover(rootPath, pattern)
    testRunner = HTMLTestRunner.HTMLTestRunner()

    reportName = "soap_report.html"
    reportPath = join(logsPath, reportName)
    reportTitle = "Soap smoke tests result for %s" % executor().getServerInfo().version
    with open(reportPath, 'w') as reportFile:
        testRunner.title = reportTitle
        testRunner.stream = reportFile
        testRunner.run(tests)

    mailer = Mailer("TestFarm", 'SoapTest@iaso.com')
    with open(reportPath, 'r') as f:
        mailer.sendMail(recipients, 'Soap smoke tests result', f.read(), [reportPath])


if __name__ == '__main__':
    options, args = parser.parse_args()
    if not options.startDir:
        sys.exit("Error: start Dir is required")
    else:
        main(options.startDir, options.pattern)
